package com.wrc.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Slf4j
public class ImportExportUtil {
    /**
     * 下载的导入模板
     *
     * @return
     */
    public static  ResponseEntity excelTemplate(String templateName, String excelSource) {
        ResponseEntity<InputStreamResource> responseEntity = null;
        try {
            // 获取文件路径 与文件流
            Resource resource = new ClassPathResource(excelSource);
            InputStream inputStream = resource.getInputStream();
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);

            // 设置响应头和内容类型
            HttpHeaders headers = new HttpHeaders();
            String encodedFileName = URLEncoder.encode(templateName, StandardCharsets.UTF_8.toString());
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + encodedFileName);
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

            // 创建响应实体对象并返回
            responseEntity = new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
            return responseEntity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }
    /**
     * 导出表格的具体方法
     *
     * @param dtoClass
     * @param list
     * @param iscount
     * @param templateName
     * @param response
     * @param <T>
     */
    public static  <T> void exportExcel(Class<T> dtoClass, List<T> list, int iscount, String templateName, String excelSource, HttpServletResponse response) {
        try {
            // 读取资源文件
            Resource resource = new ClassPathResource(excelSource);
            InputStream inputStream = resource.getInputStream();
            // 创建工作簿对象
            Workbook workbook = WorkbookFactory.create(inputStream);
            // 获取要操作的工作表
            Sheet sheet = workbook.getSheetAt(0); // 替换为实际的工作表索引或名称
            // 在工作表中写入数据
            Row headerRow = sheet.getRow(0);
            // 反射来渲染泛型数据
            for (int i = 0; i < list.size(); i++) {
                T o = list.get(i);
                Field[] beanFields = o.getClass().getDeclaredFields();
                Row beanRow = sheet.createRow(1+ i);
                for (int j = 0; j < beanFields.length; j++) {
                    Field field = beanFields[j];
                    field.setAccessible(true);
                    String value = null;
                    try {
                        Object fieldValue = field.get(o);
                        if (fieldValue != null) {
                            // 转时间
                            if (field.getType() == Date.class) {
                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                                value = dateFormat.format((Date) fieldValue);
                            } else {
                                value = fieldValue.toString();
                            }
                        } else {
                            value = "";
                        }
                    } catch (Exception e) {
                        log.error("导出表格写入数据错误");
                    }
                    Cell beanCell = beanRow.createCell(j);
                    beanCell.setCellValue(value);
                }
            }
            // 保存修改后的工作簿
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            // 下载
            try {
                templateName = URLEncoder.encode(templateName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // 设置响应头和内容类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + templateName + ".xlsx");
            // 将文件写入响应输出流
            ServletOutputStream servletOutputStream = response.getOutputStream();
            outputStream.writeTo(servletOutputStream);
            outputStream.close();
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }


    /**
     * target: 通过excel文件的列和实体字段顺序进行下标对比依次进行对号入座
     * description: 列名和实体字段必须一一对应
     */
    public static <T> List<T> subscriptParsesExcelEntities(MultipartFile excel, Class<T> dtoClass, int sheetIndex, int partyIndex) {
        List<T> dataList = new ArrayList<>();
        try {
            List<Object> read = EasyExcelFactory.read(excel.getInputStream(), new com.alibaba.excel.metadata.Sheet(1, 1));
            for (Object row : read) {
                T dto = dtoClass.getDeclaredConstructor().newInstance();
                List<String> list = (List<String>) row;
                Field[] fields = dtoClass.getDeclaredFields();
                //补缺 excel解析的时候 最后一行如果为空会被抛弃, 导致实体的fields属性List下标和读取的到的Excel的list下标不一致
                if (list.size() != fields.length) {
                    int missSum = fields.length - list.size();
                    for (int i = 0; i < missSum; i++) {
                        list.add(null);
                    }
                }
                //实体属性和excel列 对号入座
                for (int i = 0; i < fields.length; i++) {
                    Field field = fields[i];
                    field.setAccessible(true);
                    Class<?> fieldType = field.getType();
                    Object value = convertValue(list.get(i), fieldType);
                    field.set(dto, value);
                }
                dataList.add(dto);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataList;
    }

    //类型默认转换值
    private static Object convertValue(String value, Class<?> fieldType) {
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        try {
            if (fieldType == Integer.class || fieldType == int.class) {
                return Integer.parseInt(value);
            } else if (fieldType == Double.class || fieldType == double.class) {
                return Double.parseDouble(value);
            } else if (fieldType == Boolean.class || fieldType == boolean.class) {
                return Boolean.parseBoolean(value);
            } else if (fieldType == Date.class) {
                return new SimpleDateFormat("yyyy/MM/dd").parse(value);
            } else {
                return value;
            }
        } catch (NumberFormatException | ParseException E) {
            System.out.printf("值为'{}'的数据类型不对 转换失败默认返回null", value);
        }
        return  null;
    }

    public static List<List<String>> parseExcelToList(MultipartFile excelFile) throws IOException {
        List<List<String>> dataList = new ArrayList<>();
        try (InputStream inputStream = excelFile.getInputStream()) {
            EasyExcel.read(inputStream, new AnalysisEventListener<Map<Integer, String>>() {
                @Override
                public void invoke(Map<Integer, String> rowData, AnalysisContext context) {
                    // 将rowData从LinkedHashMap转换为List<String>
                    List<String> stringList = new ArrayList<>();
                    for (Map.Entry<Integer, String> entry : rowData.entrySet()) {
                        stringList.add(entry.getValue());
                    }
                    dataList.add(stringList);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    // 解析完成后的操作
                }
            }).sheet().doRead();
        }
        return dataList;
    }


    /**
     * target: 根据实体的 @ApiModelProperty的描述生成表头 并且下载导出excel
     */
    public static  <T> void exportExcelByApiModelProperty(Class<T> dtoClass, List<T> list,String templateName, HttpServletResponse response) {
        Workbook workbook = new XSSFWorkbook();
        org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet("Data");
        Field[] fields = dtoClass.getDeclaredFields();
        List<String> descriptions = new ArrayList<>();

        for (Field field : fields) {
            ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
            if (apiModelProperty != null) {
                String value = apiModelProperty.value();
                String result = String.join("", value);
                descriptions.add(result);
            }
        }
        // 渲染实体表头
        Row headerRow = sheet.createRow(0);
        CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex()); // 设置背景色为浅绿色
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font font = workbook.createFont();
        font.setBold(true); // 设置字体加粗
        headerStyle.setFont(font); // 应用字体样式
        for (int i = 0; i < descriptions.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(descriptions.get(i));
            cell.setCellStyle(headerStyle); // 应用样式
        }
        //反射来渲染泛型数据
        for (int i = 0; i < list.size(); i++) {
            T o = list.get(i);
            Field[] beanFields = o.getClass().getDeclaredFields();
            Row beanRow = sheet.createRow(1 + i);
            for (int j = 0; j < beanFields.length; j++) {
                Field field = beanFields[j];
                field.setAccessible(true);
                String value = null;
                try {
                    Object fieldValue = field.get(o);
                    if (fieldValue != null) {
                        //转时间
                        if (field.getType() == Date.class) {
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                            value = dateFormat.format((Date) fieldValue);
                        } else {
                            value = fieldValue.toString();
                        }
                    } else {
                        value = "";
                    }
                } catch (Exception e) {
                    log.error("写入数据错误");
                }
                Cell beanCell = beanRow.createCell(j);
                beanCell.setCellValue(value);
            }
        }

        //下载
        try {
            templateName = URLEncoder.encode(templateName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + templateName + ".xlsx");
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
